<template>
    <h3>网络请求</h3>
    <button @click="addData1">addData</button>
    <ul>
        <li v-for="(item,index) in messages">{{item}}</li>
    </ul>
</template>
<script setup>
import axios from 'axios';
import { onMounted,ref } from 'vue';
import api from '../api';

const messages = ref([]);

//直接调用axios
const getData = ()=>{
    axios.get('http://localhost:5000/api')
    .then(function (response) {
        messages.value = response.data.data;
    })
    .catch(function (error) {
        console.log(error);
    });
}

const getData1 = ()=>{ 
    api.getList().then(res=>{ messages.value = res.data.data; })
}

const addData = ()=>{
    axios.post('http://localhost:5000/api/add',{
        message:'this is a test message for post request'
    },{
        headers:{
            'Content-Type':'application/json'
        }
    })
    .then(function (response) {
        console.log(response);
        getData();
    })
    .catch(function (error) {
        console.log(error);
    });
}

const addData1 = ()=>{
    api.addMessage("this is new test message")
    .then(res=>{ 
        getData1(); 
    }).catch(err=>{ 
        console.log(err); 
    })
}

onMounted(()=>{
    // getData();
    getData1();
})

</script>

<style scoped></style>